import moment from 'moment'

// Map the front-end properties consistent with sever
export function createRequestFormMapping(formBaseData, submissionDetailData, changeRequirementData, taskFormData, supplementaryData, attachments, statusManagementData, riskAssessmentReviewData) {
  return {
    // formBaseData
    id: formBaseData.id,
    refNO: formBaseData.refNO,
    endorsedBy: formBaseData.endorsedBy,

    // statusManagementData
    requestStatus: statusManagementData.pcrsStatusValue,
    inchargeBy: statusManagementData.inCharge,
    requestType: statusManagementData.requestType,

    // submissionDetailData
    requesterDomainId: submissionDetailData.user.requesterDomainId,
    requesterDisplayName: submissionDetailData.user.requesterDisplayName,
    email: submissionDetailData.user.email,
    phone: submissionDetailData.user.phone,
    ttNumber: submissionDetailData.TTNo,
    ttLevel: submissionDetailData.TTOrPRLevel,
    copyTo: submissionDetailData.copyTo,
    teamName: submissionDetailData.endorserTeamId,
    changeClassification: filterClassificationOfChangeList(submissionDetailData.classificationOfChange),
    relateCategoryName: submissionDetailData.changeMainCategory,
    relateSubCategoryList: submissionDetailData.changeSubCategory,
    relatedPcrs: submissionDetailData.relatedPCRS,
    needNotifyHkctr: filterNeedNotifyHkctr(submissionDetailData.changeMainCategory),
    changeType: submissionDetailData.typeOfChange,
    changeObjective: submissionDetailData.changeObjective,
    endorserList: filterEndorserList(submissionDetailData.endorserArray),

    // changeRequirementData and riskAssessmentReviewData
    involvedPlatform: changeRequirementData.productionPlatformInvolve,
    categoryId: changeRequirementData.changeMainCategory,
    subcategoryId: changeRequirementData.changeSubCategory,
    secadminRef: changeRequirementData.secAdminReference,
    expectedDate: filterDateWithTime(changeRequirementData.expectedDateChange, changeRequirementData.expectedTimeChange.hours, changeRequirementData.expectedTimeChange.minutes),
    expectedTime: changeRequirementData.expectedTimeChange.hours + ':' + changeRequirementData.expectedTimeChange.minutes,
    riskLevel: filterRiskLevelSelect(changeRequirementData.riskLevel, changeRequirementData.isRiskLevel),
    riskAssessment: filterRiskAssessment(changeRequirementData.riskAssessment, changeRequirementData.riskLevel),
    riskAssessmentReviewResult: filterRiskAssessment(riskAssessmentReviewData.riskAssessmentReviewResult, changeRequirementData.riskLevel),
    riskAssessmentRemark: filterRiskAssessment(riskAssessmentReviewData.riskAssessmentRemark, changeRequirementData.riskLevel),
    riskAssessmentProgress: filterRiskAssessment(riskAssessmentReviewData.riskAssessmentProgress, changeRequirementData.riskLevel),
    onlineServiceImpact: filterDataByRadioSelect(changeRequirementData.onlineServiceImpactDescription, changeRequirementData.isOnlineService),
    onlineServiceImpactFromDate: filterDataByRadioSelect(changeRequirementData.onlineServiceImpact.fromDate, changeRequirementData.isOnlineService),
    onlineServiceImpactToDate: filterDataByRadioSelect(changeRequirementData.onlineServiceImpact.toDate, changeRequirementData.isOnlineService),
    systemImpact: filterDataByRadioSelect(changeRequirementData.systemPlatformImpactDescription, changeRequirementData.isSystemPlatform),
    applicationImpact: filterDataByRadioSelect(changeRequirementData.backendApplicationFunctionImpactDescription, changeRequirementData.isBackendApplication),

    // supplementaryData
    testEnv: supplementaryData.testEnvironment,
    ppTrialRunResult: supplementaryData.ppTestResult,
    testingResult: supplementaryData.qaTestResult,
    approveQATestResult: supplementaryData.approveQATestResult,
    approvePPRunResult: supplementaryData.approvePPRunResult,

    // taskFormData
    firstContactNo: taskFormData.txt1stContactNumber,
    contactNo: taskFormData.txt2ndContactNumber,
    secondVerifier: filterByNoCondition(taskFormData.txt2ndVerifierDomain, taskFormData.is2ndMoreThanOneParty),
    firstVerifier: filterByNoCondition(taskFormData.txt1stVerifierDomain, taskFormData.is1stMoreThanOneParty),
    coordinator: filterByYesCondition(taskFormData.secondCoordinator, taskFormData.is2ndMoreThanOneParty),
    firstCoordinator: filterByYesCondition(taskFormData.firstCoordinator, taskFormData.is1stMoreThanOneParty),
    hasMoreFirstVerifier: taskFormData.is1stMoreThanOneParty,
    hasMore2ndVerifier: taskFormData.is2ndMoreThanOneParty,
    workingDuriation: taskFormData.workDuration,
    verificationDuriation: taskFormData.verifyDuration,
    recoveryDuriation: filterByYesCondition(taskFormData.recoveryDuration, taskFormData.isRequireFallback),
    verificationDeadling: taskFormData.dateVerificationDeadline,
    requireFallBack: taskFormData.isRequireFallback,
    reasonOfFallbackAction: filterByNoCondition(taskFormData.noFallbackActionReason, taskFormData.isRequireFallback),
    requestprocedures: filterRequestProcedures(taskFormData.requestprocedures, taskFormData.isRequireFallback),
    disasterRecovery: 'disasterRecovery',
    firstVerificationResult: taskFormData.firstVerificationResult,
    firstVerificationReason: filterVerificationReason(taskFormData.firstVerificationReason, taskFormData.firstVerificationResult),
    firstVerificationImpact: filterVerificationReason(taskFormData.firstVerificationImpact, taskFormData.firstVerificationResult),
    verificationResult: taskFormData.verificationResult,
    verificationReason: filterVerificationReason(taskFormData.verificationReason, taskFormData.verificationResult),
    verificationImpact: filterVerificationReason(taskFormData.verificationImpact, taskFormData.verificationResult),

    // attachments
    requestattachments: filterRequestAttachments(attachments),

    importantFieldIsChanged: false,
    workingProcedureChanged: false,

    drSetupStatus: 'drSetupStatus',
    drRating: 'drRating',
    drInfo: 'drInfo',
    drSetupDate: new Date()
  }
}

// Parse data returned by sever into attributes at the front end
export function parseRequestFormData(formData) {
  return {
    formBaseData: {
      id: formData.id,
      refNO: formData.refNO,
      requesterDisplayName: formData.requesterDisplayName,
      requesterDomainId: formData.requesterDomainId
    },
    statusManagementData: {
      pcrsStatusValue: formData.requestStatus,
      inCharge: formData.inchargeBy
    },
    submissionDetailData: {
      user: {
        requesterDomainId: formData.requesterDomainId,
        email: formData.email,
        phone: formData.phone
      },
      submissionDate: moment(formData.createdAt).format('DD-MMM-YYYY HH:mm'),
      requestStatus: formData.requestStatus,
      TTNo: formData.ttNumber,
      TTOrPRLevel: formData.ttLevel,
      copyTo: formData.copyTo,
      classificationOfChange: parseClassificationOfChangeToList(formData.changeClassification),
      changeMainCategoryList: [],
      changeMainCategory: formData.relateCategoryName,
      changeSubCategory: formData.relateSubCategoryList,
      relatedPCRS: formData.relatedPcrs,
      typeOfChange: formData.changeType,
      changeObjective: formData.changeObjective,
      endorserArray: parseEndorserList(formData.endorserList),
      endorserTeamId: formData.teamName,
      endorserTeam: [],
      splitedTTNos: formData.ttNumber ? formData.ttNumber.split() : formData.ttNumber
    },
    riskAssessmentReviewData: {
      riskAssessmentReviewResult: formData.riskAssessmentReviewResult,
      riskAssessmentProgress: formData.riskAssessmentProgress,
      riskAssessmentRemark: formData.riskAssessmentRemark
    },
    changeRequirementData: {
      productionPlatformInvolve: formData.involvedPlatform,
      changeMainCategoryList: [],
      changeMainCategory: formData.categoryId,
      changeSubCategory: formData.subcategoryId,
      secAdminReference: formData.secadminRef,
      expectedDateChange: parseExpectedDate(formData.expectedDate, formData.expectedTime.split(':')[0], formData.expectedTime.split(':')[1]),
      expectedTimeChange: {
        hours: formData.expectedTime.split(':')[0],
        minutes: formData.expectedTime.split(':')[1]
      },
      onlineServiceImpact: {
        fromDate: parseDate(formData.onlineServiceImpactFromDate),
        toDate: parseDate(formData.onlineServiceImpactToDate)
      },
      onlineServiceImpactDescription: formData.onlineServiceImpact,
      isOnlineService: parseChangeRequirementRadioStatus(formData.onlineServiceImpact),
      systemPlatformImpactDescription: formData.systemImpact,
      isSystemPlatform: parseChangeRequirementRadioStatus(formData.systemImpact),
      backendApplicationFunctionImpactDescription: formData.applicationImpact,
      isBackendApplication: parseChangeRequirementRadioStatus(formData.applicationImpact),
      isRiskLevel: parseRiskLevel(formData.riskLevel),
      riskLevel: formData.riskLevel,
      riskAssessment: formData.riskAssessment
    },
    supplementaryData: {
      testEnvironment: formData.testEnv,
      ppTestResult: formData.ppTrialRunResult,
      qaTestResult: formData.testingResult,
      approveQATestResult: formData.approveQATestResult,
      approvePPRunResult: formData.approvePPRunResult
    },
    taskFormData: {
      txt2ndVerifierDomain: formData.secondVerifier,
      txt1stVerifierDomain: formData.firstVerifier,
      txt1stContactNumber: formData.firstContactNo,
      txt2ndContactNumber: formData.contactNo,
      secondCoordinator: formData.coordinator,
      firstCoordinator: formData.firstCoordinator,
      isRequireFallback: formData.requireFallBack,
      is1stMoreThanOneParty: formData.hasMoreFirstVerifier,
      is2ndMoreThanOneParty: formData.hasMore2ndVerifier,
      workDuration: formData.workingDuriation,
      verifyDuration: formData.verificationDuriation,
      recoveryDuration: formData.recoveryDuriation,
      dateVerificationDeadline: parseDate(formData.verificationDeadling),
      noFallbackActionReason: formData.reasonOfFallbackAction,
      requestprocedures: formData.requestprocedures,
      firstVerificationResult: formData.firstVerificationResult,
      firstVerificationReason: formData.firstVerificationReason,
      firstVerificationImpact: formData.firstVerificationImpact,
      verificationResult: formData.verificationResult,
      verificationReason: formData.verificationReason,
      verificationImpact: formData.verificationImpact
    },
    attachments: parseAttachments(formData.requestattachments)
  }
}

// the filter method
const filterNeedNotifyHkctr = (category) => {
  if (category) {
    return 1
  } else {
    return 0
  }
}

const filterEndorserList = (endorserArray) => {
  return endorserArray.join(';')
}

const filterClassificationOfChangeList = (classificationOfChange) => {
  return classificationOfChange.join(';')
}

const filterDateWithTime = (date, hours, minutes) => {
  return moment(date).add({hours: hours, minutes: minutes})
}

const filterRequestAttachments = (attachments) => {
  let requestattachments = []
  attachments.forEach((attachment) => {
    let requestattachment = {}
    let {...otherParams} = attachment
    requestattachment.attachment = otherParams
    requestattachment.description = 'description'
    requestattachment.status = '1'
    requestattachments.push(requestattachment)
  })
  return requestattachments
}

const filterDataByRadioSelect = (data, select) => {
  if (select === 'Yes') {
    return data
  } else {
    return ''
  }
}

const filterRequestProcedures = (data, select) => {
  setSeqToProcedureItemWithType(data, 'Working')
  setSeqToProcedureItemWithType(data, 'Verify')
  setSeqToProcedureItemWithType(data, 'Recovery')
  if (select === 'Yes') {
    return data
  } else {
    return data.filter(item => item.procedureType !== 'Recovery')
  }
}

const setSeqToProcedureItemWithType = (data, type) => {
  let count = 1
  data.forEach(item => {
    if (item.procedureType === type) {
      item.procedureSeq = count++
    }
  })
}

const filterByYesCondition = (data, select) => {
  if (select === 'Yes') {
    return data
  } else {
    return ''
  }
}

const filterByNoCondition = (data, select) => {
  if (select === 'No') {
    return data
  } else {
    return ''
  }
}

const filterRiskLevelSelect = (data, select) => {
  if (select === true) {
    return data
  } else {
    return ''
  }
}

const filterRiskAssessment = (data, select) => {
  if (select === 'High' || select === 'Medium') {
    return data
  } else {
    return ''
  }
}

const filterVerificationReason = (data, select) => {
  if (select === 'Fail') {
    return data
  } else {
    return ''
  }
}

// the parse method
const parseClassificationOfChangeToList = (classificationOfChange) => {
  if (classificationOfChange) {
    return classificationOfChange.split(';')
  } else {
    return ''
  }
}

const parseAttachments = (attachments) => {
  let result = []
  attachments.forEach((item) => {
    let {attachment} = item
    result.push(attachment)
  })
  return result
}

const parseDate = (date) => {
  if (date) {
    return new Date(date)
  } else {
    return date
  }
}

const parseExpectedDate = (date, hours, minutes) => {
  let expectedDate = moment(date).subtract({hours: hours, minutes: minutes})
  return parseDate(expectedDate.toDate())
}

const parseEndorserList = (endorserList) => {
  return endorserList.split(';')
}

const parseRiskLevel = (content) => {
  if (content) {
    return true
  } else {
    return false
  }
}

const parseChangeRequirementRadioStatus = (content) => {
  if (content) {
    return 'Yes'
  } else {
    return 'No'
  }
}
